﻿$(document).ready(function () {

    var playlist;
    var newPlaylist = [];

    /**Lyrics-AddSongs-MakeList Display **/
    var showLyrics = false;
    var showAdd = false;
    var showMakelist = false;

    function DisplayLyrics(show) {
        if (show) {
            $("#SongLyrics").show();
            showLyrics = true;
            $("#showLyrics").text('Hide');
        }
        else {
            $("#SongLyrics").hide();
            showLyrics = false;
            $("#showLyrics").text('Show');
        }
    }
    function DisplayAdd(show) {
        if (show) {
            $("#AddSongs").show();
            showAdd = true;
            $("#showAdd").text('Hide');
        }
        else {
            $("#AddSongs").hide();
            showAdd = false;
            $("#showAdd").text('Show');
        }
    }
    function DisplayMakeList(show) {
        if (show) {
            $("#makeList").show();
            showMakelist = true;
            $("#showMakeList").text('Hide');
        }
        else {
            $("#makeList").hide();
            showMakelist = false;
            $("#showMakeList").text('Show');
        }
    }
    function WindowCheck() {
        if (window.innerWidth > 500) {
            DisplayMakeList(true);
            DisplayLyrics(true);
            DisplayAdd(true);
        }
        else {
            DisplayMakeList(showMakelist);
            DisplayLyrics(showLyrics);
            DisplayAdd(showAdd);
        }
    }
    WindowCheck();
    $("#showLyrics").click(function () {
        DisplayLyrics(!showLyrics);
    });
    $("#showMakeList").click(function () {
        DisplayMakeList(!showMakelist);
    });
    $("#showAdd").click(function () {
        DisplayAdd(!showAdd);
    });

    
    /************/


    var display = "comp";
    if (navigator.userAgent.match(/Android/i)
         || navigator.userAgent.match(/webOS/i)
         || navigator.userAgent.match(/iPhone/i)
         || navigator.userAgent.match(/iPad/i)
         || navigator.userAgent.match(/iPod/i)
         || navigator.userAgent.match(/BlackBerry/i)
         ) { display = "phone" }
    
    /* Playlist options */
    var options = {
        autoPlay: false,
        errorMsg: "Custom error message",
        showplaylist: !(display == "phone")
    }

    // Load playlist with all available songs
    loadPlaylist(playlist, options);

    /* Search events */
    $("#search").focus(function () {
        if (this.value == "SEARCH") {
            this.value = '';
            $(this).css('color', '#000');
        }
    });
    $("#search").change(function () {
        if (this.value == '') {
            this.value = "SEARCH";
            $(this).css('color', '#ccc');
        }
    });
    $("#search").keypress(function (e) {
        if (this.value != '') {
            searchPlaylist(this.value);
        }
    });
    $("#QueryResults li").live('click', function () {
        getSongById(this.id, false);    // false not current song
    });

    /* Build custom playlist events */
    $("#addToPlaylist").click(function () {
        addSongById(newPlaylist, $("#songToAdd").val());
        $("#playlistOptions").show();

    });
    $("#loadPlaylist").live('click', function () {
        $("#thePlayer").empty();
        if (newPlaylist.length > 0)
        {
            $("#thePlayer").musicPlayer(newPlaylist, options);
            $("#progress-bar").width($("#progress-wrapper").width());
        }
    });
    $("#clearPlaylist").live('click', function () {
        $("#playlistToLoad").empty();
        newPlaylist = [];
        $("#playlistOptions").hide();
    });

    /* MusicPlayer/Current song events */
    $("#hidden").bind('change', function () {   // Event triggered by music-player when song changes
        getSongById(this.value, true);          // true current, false not current
    });
    $("#updateInfo").click(function () {
        showInfoForm($("#hidden").val());
    });
    $("#updateInfoSubmit").click(function () {
        submitInfo($("#hidden").val());
    });
    $(window).resize(function () {
        WindowCheck();
        $("#progress-bar").width($("#progress-wrapper").width());
    });

    /* Upload song */
    $("#uploadForm").ajaxForm(function () {
        $("#UploadSuccess").show().fadeOut(3600, "linear");   
        $("#uploadForm").clearForm();
    });
}); /* /document.ready */

// Loads the musicPlayer with all available songs
function loadPlaylist(playlist, options) {
    var request = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '/api/playlist'
    });
    request.done(function (data) {
        playlist = data;
        $("#thePlayer").musicPlayer(playlist, options);
        $("#progress-bar").width($("#progress-wrapper").width());
    });
    request.fail(function (xhr, msg, error) {
        $("#errorMsg").text("Error: Load playlist failed");
        $("#errorMsg").show().fadeOut(3600, "linear");
    });
}
// Accepts a query string and populates corresponding search results
function searchPlaylist(query) {
    var request = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '/api/playlist?query=' + query
    });
    request.done(function (data) {
        $("#QueryResults").empty();

        $.each(data, function (key, val) {
            listElem = document.createElement("li");
            $(listElem).text(val.Artist + " - " + val.Name);
            $(listElem).attr("id", val.Id);
            $(listElem).appendTo("#QueryResults");
        });
        if (data != 0) {
            $("#noResults").hide();
        }
        else{
            $("#noResults").show();
        }
    });
    request.fail(function (xhr, msg, error) {
        $("#errorMsg").text("Error: Search failed");
        $("#errorMsg").show().fadeOut(3600, "linear");
    });
}

/* Adds a song (by id) to a given playlist */
function addSongById(playlist, id) {
    var request = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '/api/song?id=' + id
    });
    request.done(function (data) {
        playlist.push([data.Src, data.Name, data.Id]);
        $("#playlistTemplate").tmpl(data).appendTo("#playlistToLoad");
    });
    request.fail(function (xhr, msg, error) {
        $("#errorMsg").text("Error: Couldn't add song");
        $("#errorMsg").show().fadeOut(3600, "linear");
    });
}

/* Retrieves info and publishes update info form */
function showInfoForm(id) {
    var request = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '/api/song?id=' + id
    });
    request.done(function (data) {
        $("#updateArtist").val(data.Artist);
        $("#updateSongTitle").val(data.Name);
        $("#updateGenre").val(data.Genre);
        $("#updateInfoForm").show();
    });
    request.fail(function (xhr, msg, error) {
        $("#errorMsg").text("Error: Couldn't get information");
        $("#errorMsg").show().fadeOut(3600, "linear");
    });
}

/* Updates info of a particular song */
function submitInfo(id) {
    var title = $("#updateSongTitle").val();
    if (title == '') {
        $("#updateError").show().fadeOut(3600, "linear");
    }
    else {
        var artist = $("#updateArtist").val();
        if (artist == '') {
            artist = 'Unknown';
        }
        var genre = $("#updateGenre").val();
        var request = $.ajax({
            type: 'PUT',
            data: { "id": id, "title": title, "artist": artist, "genre": genre },
            dataType: 'json',
            url: '/api/song/'
        });
        request.done(function (data) {
            getSongById(id, true);
            $("#updateInfoForm").hide();
        });
        request.fail(function (xhr, msg, error) {
            $("#errorMsg").text("Error: Couldn't upload song");
            $("#errorMsg").show().fadeOut(3600, "linear");
        });
    }
}

/* Retrieves and publishes information about a song/artist
 * given a song id. Second parameter indicates whether 
 * the info should be published for the current song
 * or a search result */
function getSongById(id, current) {
    var request = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: '/api/song?id=' + id
    });
    request.done(function (data) {
        if (current) {
            $("#updateInfoForm").hide();
            $("#artist").text(data.Artist);
            $("#genre").text(data.Genre);
            getArtistInfo(data.Artist, current);
            getSongInfo(data.Name);
            if (data.Artist == 'Unknown'){
                $("#infoHead").hide();
            }
            else {
                $("#infoHead").show();
            }
        }
        else {
            var songInfo = data.Name;
            if (data.Artist != 'Unknown')
                songInfo += ' by ' + data.Artist;
            if (data.Genre != null)
                songInfo += ' (' + data.Genre + ') ';
            $("#browseSong").text(songInfo);
            $("#songToAdd").val(data.Id);
            getArtistInfo(data.Artist, current);
            $("#BrowseInfo").show();
        }
    });
    request.fail(function (xhr, msg, error) {
        $("#errorMsg").text("Error: Couldn't find song info");
        $("#errorMsg").show().fadeOut(3600, "linear");
    });
}

/* Retrieves and publishes information about artist
 * from GuitarParty.com. Second parameter indicates whether 
 * the info should be published for the current song
 * or a search result */
function getArtistInfo(artist, current) {
    var API_KEY = "3a13d51319712f673b7455ec41c623efd001d562";
    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Guitarparty-Api-Key', API_KEY);
        }
    });
    var request = $.ajax({
        dataType: 'json',
        type: 'GET',
        url: 'http://api.guitarparty.com/v2/artists/?query=' + artist
    });
    request.done(function (data) {
        if (data.objects_count == 0) {  // no match
            if (current)
                $("#bio").html('');
            else
                $("#browseBio").html('');
        }
        $.each(data.objects, function (key, val) {
            if (artist == val.name) {
                if (current)
                    $("#bio").html(val.bio);
                else
                    $("#browseBio").html(val.bio);
            }
        });
    });
    request.fail(function (xhr, msg, error) {
        $("#errorMsg").text("Error: GuitarParty Error");
        $("#errorMsg").show().fadeOut(3600, "linear");
    });
}

/* Retrieves and publishes lyrics for a song
* from GuitarParty.com. */
function getSongInfo(song) {   
    var API_KEY = "3a13d51319712f673b7455ec41c623efd001d562";
    $.ajaxSetup({
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Guitarparty-Api-Key', API_KEY);
        }
    });
    var request = $.ajax({
        dataType: 'json',
        type: 'GET',
        url: 'http://api.guitarparty.com/v2/songs/?query=' + song
    });
    request.done(function (data) {
        if (data.objects_count == 0) {  // no match
            $("#lyrics").html('<p style="color: #999;"> Unable to find lyrics to this song </p>');
        }
        $.each(data.objects, function (key, val) {
            if (song == val.title) {
                $("#lyrics").html(val.body);
            }
        });

    });
    request.fail(function (xhr, msg, error) {
        $("#errorMsg").text("Error: GuitarParty Error");
        $("#errorMsg").show().fadeOut(3600, "linear");
    });
}
